package com.tarena.lbs.coupon.dao.repository.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.coupon.dao.mapper.CouponMapper;
import com.tarena.lbs.coupon.dao.repository.CouponRepository;
import com.tarena.lbs.coupon.pojo.po.CouponPO;
import com.tarena.lbs.coupon.pojo.query.CouponQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Slf4j
@Repository
public class CouponRepositoryImpl implements CouponRepository {

    @Autowired
    private CouponMapper couponMapper;

    @Override
    public PageInfo<CouponPO> pageList(CouponQuery query) {
        log.debug("分页查询优惠券列表，入参：{}", query);
        
        // 启动分页
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        
        // 执行查询
        List<CouponPO> couponList = couponMapper.getCouponList(query);
        
        // 封装分页信息
        PageInfo<CouponPO> pageInfo = new PageInfo<>(couponList);
        
        log.debug("分页查询优惠券列表成功，共{}条数据", pageInfo.getTotal());
        return pageInfo;
    }

    @Override
    public CouponPO getById(Integer id) {
        log.info("=== CouponRepositoryImpl.getById 开始 ===");
        log.info("根据ID查询优惠券，ID：{}", id);
        
        try {
            CouponPO result = couponMapper.selectById(id);
            log.info("数据库查询结果：{}", result);
            log.info("=== CouponRepositoryImpl.getById 结束 ===");
            return result;
        } catch (Exception e) {
            log.error("数据库查询异常：{}", e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public void save(CouponPO couponPO) {
        log.debug("保存优惠券，入参：{}", couponPO);
        couponMapper.insert(couponPO);
        log.debug("保存优惠券成功，ID：{}", couponPO.getId());
    }

    @Override
    public void update(CouponPO couponPO) {
        log.debug("更新优惠券，入参：{}", couponPO);
        couponMapper.updateById(couponPO);
        log.debug("更新优惠券成功，ID：{}", couponPO.getId());
    }
}
